import dayjs from 'dayjs';
import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Button } from '@tarojs/components';

import { MyCoachItem } from '../../types/myself';
import { getMyCoachInfoApi } from '../../api/myself';
import ImageLoader from '../../components/ImageLoader';
import { PageHeader } from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import { UserGenderImage } from '../../components/userGender';
import { DataLoadingView } from '../../components/dataLoading';
import { generateInitialSlots } from '../../utils/smartAssign';
import { AppointTimeDataItem, AppointApplyResultSchema } from '../../types/appoint';
import {
  addAppointApplyApi, cancelAppointApplyApi, 
  getAppointResultApi, getAppointApplyApi 
} from '../../api/appoint';

import './index.scss';

/**
 * 用户时间预约页面组件
 * 用于用户预约练车时间
 */
const UserTimeAppointPage: React.FC = () => {
  // 状态管理
  const { userInfo } = useAppContext();
  const userId = Number(userInfo?.id);
  const firstLoadRef = useRef<boolean>(false);
  const [coachId, setCoachId] = useState<number>(0);
  const [coachInfo, setCoachInfo] = useState<MyCoachItem | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [selectedDate, setSelectedDate] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [selectedSubject, setSelectedSubject] = useState<string>('2'); // 默认选择科目二
  const [myAppointment, setMyAppointment] = useState<AppointApplyResultSchema | null>(null);
  const [showSuccessModal, setShowSuccessModal] = useState<boolean>(false);
  const [appointmentStatus, setAppointmentStatus] = useState<number>(0); // 0: 未预约, 1: 已预约, 2: 已取消
  const [showEvening, setShowEvening] = useState<boolean>(false);
  const [showEarlyMorning, setShowEarlyMorning] = useState<boolean>(false);
  const [workTime, setWorkTime] = useState<string[]>(['09:00:00', '18:00:00']);
  const [userResult, setUserResult] = useState<AppointTimeDataItem | null>(null);
  const [vehiclePages, setVehiclePages] = useState<AppointTimeDataItem[] | null>(null);
  const [currentDate, setCurrentDate] = useState(dayjs());
  const TomorrowDay = dayjs().add(1, 'day');
  const Tomorrow = TomorrowDay.format('YYYY-MM-DD');

  // 初始化数据
  useEffect(() => {
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfo();
    }
  }, []);

  // 科目变化时重新获取时间段
  useEffect(() => {
    if (coachId) {
      fetchTimeSlots();
    }
  }, [selectedSubject]);

  // 获取初始信息
  const getInitInfo = async () => {
    try {
      setLoading(true);
      // 判断当前时间是否大于18点
      let now = dayjs();
      if (now.hour() >= 18) {
        // 如果大于18点，显示明天的预约
        now = now.add(1, 'day');
        setCurrentDate(now);
        setSelectedDate(now.format('YYYY-MM-DD'));
      } 

      const res = await getMyCoachInfoApi();
      if (res.code === 200 && res.data) {
        setCoachInfo(res.data);
        const coach_id = res.data.coach.id;
        setCoachId(coach_id);
        setWorkTime([
          res.data.coach.work_start_time || '09:00:00', 
          res.data.coach.work_end_time || '18:00:00'
        ]);
        if (coach_id) {
          getAppointApplyApi(coach_id, Tomorrow).then(resp => {
            if(resp.code === 0) {
              setMyAppointment(resp.data);
              if(resp.data && resp.data.subject) {
                setSelectedSubject(resp.data.subject);
              }
            }
          })
          fetchTimeSlots();
        }
      } else {
        Taro.showToast({ title: '获取教练信息失败', icon: 'none' });
      }
    } catch (error) {
      console.error('获取初始信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取时间段
  const fetchTimeSlots = async () => {
    try {
      setVehiclePages([]);
      const res = await getAppointResultApi(coachId, currentDate.format('YYYY-MM-DD'), Number(selectedSubject));
      if (res.code === 200 && res.data) {
        if (res.data.status === 2) {
          setUserResult(null);
          const newVehiclePages = generateInitialSlots(
            dayjs(`${currentDate.format('YYYY-MM-DD')} ${workTime[0]}`, 'YYYY-MM-DD HH:mm:ss'),
            dayjs(`${currentDate.format('YYYY-MM-DD')} ${workTime[1]}`, 'YYYY-MM-DD HH:mm:ss'),
            currentDate, 2);
          setVehiclePages(newVehiclePages);
        } else if (res.data && res.data.record && res.data.record.length > 0) {
          setVehiclePages(res.data.record);
          // 检查是否有用户的预约
          res.data.record.forEach((item: AppointTimeDataItem) => {
            if (item.studentId === userId) {
              setUserResult(item);
            }
          });
        } else {
          setUserResult(null);
          const newVehiclePages = generateInitialSlots(
            dayjs(`${currentDate.format('YYYY-MM-DD')} ${workTime[0]}`, 'YYYY-MM-DD HH:mm:ss'),
            dayjs(`${currentDate.format('YYYY-MM-DD')} ${workTime[1]}`, 'YYYY-MM-DD HH:mm:ss'),
            currentDate);
          setVehiclePages(newVehiclePages);
        }
      } else {
        console.log(res?.message || '获取排班表失败');
        Taro.showToast({ title: '获取排班表失败，请稍后重试~', icon: 'none' });
      }
    } catch (error) {
      console.error('获取时间段失败:', error);
      Taro.showToast({ title: '获取时间段失败', icon: 'none' });
    }
  };

  // 预约操作
  const userApplyCarAppoint = async (period: number) => {
    const data = {
      coach_id: coachId,
      date: Tomorrow,
      period: period,
      subject: selectedSubject,
    };

    if (!selectedSubject || !coachId) {
      Taro.showToast({ title: '请选择课程和教练', icon: 'none' });
      return;
    }

    try {
      setLoading(true);
      const res = await addAppointApplyApi(data);
      if (res.code === 200) {
        Taro.showToast({ title: '预约成功', icon: 'success' });
        setMyAppointment(res.data);
        setShowSuccessModal(true);
        await fetchTimeSlots();
      } else {
        Taro.showToast({ title: res.message || '预约失败', icon: 'none' });
      }
    } catch (error) {
      console.error('预约失败:', error);
      Taro.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      setLoading(false);
    }
  };

  // 选择科目
  const handleSubjectSelect = (subject: string) => {
    setSelectedSubject(subject);
  };
  
  // 切换上午时间段展开/收起
  const toggleEarlyMorning = () => {
    setShowEarlyMorning(!showEarlyMorning);
  };
  
  // 切换下午时间段展开/收起
  const toggleEvening = () => {
    setShowEvening(!showEvening);
  };

  // 取消预约
  const handleCancelAppointment = async () => {
    if (!coachInfo || !myAppointment) return;

    Taro.showModal({
      title: '取消预约',
      content: '确定要取消此次预约吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            setLoading(true);
            const result = await cancelAppointApplyApi(myAppointment.id, coachInfo.coach.id);
            if (result.code === 0 && result.data) {
              Taro.showToast({ title: '取消成功', icon: 'success' });
              setAppointmentStatus(2);
              setMyAppointment(null);
              await fetchTimeSlots();
            } else {
              Taro.showToast({ title: result.message || '取消失败', icon: 'none' });
            }
          } catch (error) {
            console.error('取消预约失败:', error);
            Taro.showToast({ title: '网络错误', icon: 'none' });
          } finally {
            setLoading(false);
          }
        }
      }
    });
  };

  // 获取时间段状态样式
  const statusBgColor = (status: number, studentId: number) => {
    if (status === 4  || status === 2) {
      return "rest";
    } else if (status === 0) {
      return "unappointed";
    } else if (status === 3) {
      return "closed";
    } else if (status === 1 && studentId === userId) {
      return "my-appointed";
    } else if (status === 1) {
      return "appointed";
    }
    return "";
  };

  // 渲染教练信息卡片
  const renderCoachCard = () => {
    if (!coachInfo) return null;

    return (
      <View className="time-appoint-coach-card">
        <View className="time-appoint-card-body">
          <View className="time-appoint-coach-avatar-section">
            <ImageLoader
            className="time-appoint-coach-avatar"
            src={coachInfo.coach.avatar}
            mode="aspectFill"
          />
          </View>

          <View className="time-appoint-coach-info">
            <View className="time-appoint-coach-name-section">
              <Text className="time-appoint-coach-name">{coachInfo.coach.username}</Text>
              <UserGenderImage gender={coachInfo.coach.gender || ''} />
            </View>
            
            <View className="time-appoint-coach-tags">
              <View className="purple-tag text-base">{coachInfo.coach.age}岁</View>
              <View className="magenta-tag text-base">教龄{coachInfo.coach.experience_years}年</View>
              <View className="lime-tag text-base">籍贯:{coachInfo.coach.native}</View>
            </View>
          </View>

          <View className="time-appoint-coach-details">
            {workTime && workTime.length === 2 && (
              <View className="cyan-tag text-base">
                工作时间:
                <View className="text-base">{workTime[0]} ~ {workTime[1]}</View>
              </View>
            )}
            <View className="purple-tag text-base">{coachInfo.city_base.name}</View>
            <View className="magenta-tag text-base">{coachInfo.coach.school}</View>
          </View>
        </View>
      </View>
    );
  };

  // 渲染日期选择
  const renderDateSelection = () => {
    return (
      <View className="time-appoint-date-selection">
        <View className="time-appoint-calendar-header">
          <Text className="time-appoint-calendar-title">
              <MaterialIcons name="event" className="time-appoint-title-icon" size={16} />
              {currentDate.format('YYYY-MM-DD')} 上车练习排班表
            </Text>
        </View>
      </View>
    );
  };

  // 渲染科目选择
  const renderSubjectSelection = () => {
    return (
      <View className="time-appoint-subject-selection">
        <View className="time-appoint-card-title">
          <View className="time-appoint-title-content">
            <Text className="time-appoint-title-text">我要预约</Text>
          </View>
          <View className="time-appoint-subject-tabs">
            <View
              className={`time-appoint-subject-tab ${selectedSubject === '2' ? 'selected' : ''}`}
              onClick={() => handleSubjectSelect('2')}
            >
              科目二
            </View>
            <View
              className={`time-appoint-subject-tab ${selectedSubject === '3' ? 'selected' : ''}`}
              onClick={() => handleSubjectSelect('3')}
            >
              科目三
            </View>
          </View>
        </View>
      </View>
    );
  };

  // 获取时间段状态文本
  const getTimeSlotStatusText = (status: number): string => {
    switch (status) {
      case 0:
        return '未预约';
      case 1:
        return '已预约';
      case 2:
        return '外勤';
      case 3:
        return '未开放';
      case 4:
        return '休息';
      default:
        return '';
    }
  };

  // 获取时间段状态颜色类名
  const getTimeSlotStatusColorClass = (status: number): string => {
    switch (status) {
      case 0:
        return 'time-appoint-text-blue-500';
      case 1:
        return 'time-appoint-text-red-500';
      case 2:
        return 'time-appoint-text-blue-500';
      case 3:
        return 'time-appoint-text-yellow-500';
      case 4:
        return 'time-appoint-text-yellow-500';
      default:
        return '';
    }
  };

  // 渲染时间段
  const renderTimeSlots = () => {
    return (
      <View className="time-appoint-time-slots-section">
        <View className="time-appoint-time-slot-container">
          <View 
            className="time-appoint-flex"
            onClick={() => toggleEarlyMorning()}>
            <Text className="time-appoint-icon">{showEarlyMorning ? '▼' : '▶'}</Text>
            <Text>{showEarlyMorning ? `收起 00:00-${workTime[0]}` : `展开 00:00-${workTime[0]}`}</Text>
          </View>
          <View 
            className="time-appoint-flex"
            onClick={() => toggleEvening()}>
            <Text className="time-appoint-icon">{showEvening ? '▼' : '▶'}</Text>
            <Text>{showEvening ? `收起 ${workTime[1]}-24:00` : `展开 ${workTime[1]}-24:00`}</Text>
          </View>
        </View>

        <View className="time-slot-grid">
         {vehiclePages && vehiclePages.map((currentSlot, index) => {
            // 检查是否在工作时间内
            console.log('currentSlot', currentSlot);

            if ((currentSlot.isMorningSlot && !showEarlyMorning) || (currentSlot.isEveningSlot && !showEvening)) {
              return null;
            }

            const isOpen = !(currentSlot.status === 2 || currentSlot.status === 4);
            const isMe = currentSlot.status === 1 && currentSlot.studentId === userId;
            const statusClass = statusBgColor(currentSlot.status, currentSlot.studentId || 0);
            const statusText = getTimeSlotStatusText(currentSlot.status);
            const statusColorClass = getTimeSlotStatusColorClass(currentSlot.status);

            return (
              <View 
                key={index} 
                className={`time-appoint-time-slot ${isOpen ? 'available' : 'unavailable'} ${statusClass}`}
              >
                <View className="time-appoint-time-slot-content">
                  <View className="time-appoint-time-slot-header">
                    {isMe ? (
                      <View className="time-appoint-my-appointment-indicator">
                        <Text className="time-appoint-time-text time-appoint-my-time">{currentSlot.display}</Text>
                      </View>
                    ) : (
                      <Text className="time-appoint-time-text">{currentSlot.display}</Text>
                    )}
                    {currentSlot.status === 4 && (
                      <Text className="time-appoint-sun-icon">☀</Text>
                    )}
                  </View>
                  <Text className={`time-appoint-appoint-status ${statusColorClass} ${currentSlot.status === 4 ? 'time-appoint-appoint-rest-status' : ''} ${isMe ? 'time-appoint-appoint-my-status' : ''}`}>
                    {isMe ? '我的预约' : statusText}
                  </Text>
                </View>
              </View>
            );
          })}
        </View>
      </View>
    );
  };

  // 渲染我的预约信息
  const renderMyAppointment = () => {
    if (!myAppointment) return null;

    return (
      <View className="time-appoint-my-appointment-card" style={{ backgroundColor: '#e6f7ff', border: '1px solid #91d5ff', borderRadius: '4px', padding: '16px', marginBottom: '16px' }}>
        <View className="time-appoint-appointment-info" style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: '12px' }}>
          <Text style={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}>您已预约</Text>
          <Text className="time-appoint-info-label" style={{ marginLeft: '16px' }}>日期: </Text>
          <Text className="time-appoint-info-value"><Text className="time-appoint-font-bold">{myAppointment.date}</Text></Text>
          <Text className="time-appoint-info-label" style={{ marginLeft: '16px' }}>时间段: </Text>
          <Text className="time-appoint-info-value"><Text className="time-appoint-font-bold">{myAppointment.period === 0 ? "全天 (6:00-20:00)" : myAppointment.period === 1 ? "上午 (6:00-12:00)" : "下午 (12:00-20:00)"}</Text></Text>
          <Text className="time-appoint-info-label" style={{ marginLeft: '16px' }}>科目: </Text>
          <Text className="time-appoint-info-value"><Text className="time-appoint-font-bold">{myAppointment.subject === '2' ? '科目二' : '科目三'}</Text></Text>
        </View>
        
        <View className="time-appoint-appointment-info" style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: '12px' }}>
          <Text style={{ color: '#ff4d4f', fontSize: '22px', fontWeight: 'bold' }}>教练分配给您的学习时间信息:</Text>
          {userResult ? (
            <View style={{ display: 'flex', flexDirection: 'row', marginLeft: '16px' }}>
              <Text className="time-appoint-info-label">科目: </Text>
              <Text className="time-appoint-info-value"><Text className="time-appoint-font-bold">{userResult.subject === '2' ? '科目二' : '科目三'}</Text></Text>
              <Text className="time-appoint-info-label" style={{ marginLeft: '16px' }}>时长: </Text>
              <Text className="time-appoint-info-value"><Text className="time-appoint-font-bold">{userResult.duration}小时</Text></Text>
              <Text className="time-appoint-info-label" style={{ marginLeft: '16px' }}>时间段: </Text>
              <Text className="time-appoint-info-value"><Text className="time-appoint-font-bold">{userResult.display}</Text></Text>
            </View>
          ) : (
            <View className="time-appoint-info-row" style={{ marginLeft: '16px' }}>
              <Text>当期日期:{currentDate.format('YYYY年MM月DD日')}，教练暂无分配</Text>
            </View>
          )}
        </View>
        
        <View className="time-appoint-alert-warning" style={{ backgroundColor: '#fff7e6', border: '1px solid #ffe7ba', borderRadius: '4px', padding: '12px', marginBottom: '16px' }}>
          <Text className="time-appoint-alert-title" style={{ color: '#d48806', fontWeight: 'bold', marginBottom: '8px', display: 'block' }}>温馨提示</Text>
          <View className="time-appoint-alert-content">
            <Text>您已预约学车时段，请提前15分钟左右抵达学车地点，以免耽误您的练习时间。</Text>
            <Text>如您需要取消预约，请点击下方按钮，并且通知教练。</Text>
            <Text>如您需要修改预约时间，请联系教练。</Text>
          </View>
        </View>
        
        <Button
          className="time-appoint-cancel-btn"
          type="default"
          onClick={handleCancelAppointment}
          style={{ backgroundColor: '#ff4d4f', color: '#fff', width: '100%' }}
        >
          取消预约
        </Button>
      </View>
    );
  };

  // 渲染预约成功弹窗
  const renderSuccessModal = () => {
    if (!showSuccessModal) return null;

    return (
      <View className="time-appoint-success-modal">
        <View className="time-appoint-modal-content">
          <View className="time-appoint-success-icon-container">
            <MaterialIcons name="check-circle" size={24} />
          </View>
          <Text className="time-appoint-success-text">预约成功！</Text>
          <Text className="time-appoint-success-subtext">请准时参加练习</Text>
          <Button
            className="time-appoint-confirm-btn"
            type="primary"
            onClick={() => setShowSuccessModal(false)}
          >
            确定
          </Button>
        </View>
      </View>
    );
  };

  // 渲染底部提示
  const renderBottomTips = () => {
    return (
      <View className="time-appoint-bottom-tips">
        <View className="time-appoint-tips-content">
            <MaterialIcons name="info" size={20} />
            <Text className="time-appoint-tip-text">
              温馨提示：请提前24小时取消预约，否则将影响您的预约信用。
            </Text>
          </View>
      </View>
    );
  };

  const renderAppointmentButtons = () => {
    if (myAppointment) return null;

    return (
      <View className="time-appoint-appointment-buttons">
        <View className="time-appoint-appointment-button-container">
          <Button
            className="time-appoint-appointment-button time-appoint-morning"
            onClick={() => userApplyCarAppoint(1)}
          >
            预约上午 (6:00-12:00)
          </Button>
          <Button
            className="time-appoint-appointment-button time-appoint-afternoon"
            onClick={() => userApplyCarAppoint(2)}
          >
            预约下午 (12:00-20:00)
          </Button>
          <Button
            className="time-appoint-appointment-button time-appoint-all-day"
            onClick={() => userApplyCarAppoint(0)}
          >
            预约全天 (6:00-20:00)
          </Button>
        </View>
      </View>
    );
  };

  return (
    <View className="time-appoint-page-container">
      <PageHeader title="练车预约" />
      {loading && (<DataLoadingView />)}
      <View className="time-appoint-content-wrapper">
        {renderCoachCard()}
        {renderDateSelection()}
        {renderSubjectSelection()}
        {renderMyAppointment()}
        {renderTimeSlots()}
        {renderAppointmentButtons()}
        {renderBottomTips()}
      </View>
      {renderSuccessModal()}
    </View>
    );
  };

export default UserTimeAppointPage;